package com.wang.interceptors;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wang.utils.ConstantUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Classname ApiInterceptor
 * @Description TODO
 * @Date 2025/3/24 11:08
 * @Created by pc
 */
@Component
@Slf4j
public class ApiInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 请求之前要判断用户是否登录 如果没有登录 不允许访问后续接口
        HttpSession session = request.getSession();
        Object loginUser = session.getAttribute(ConstantUtil.LOGIN_USER);
        if(loginUser == null){
            log.warn("用户未登录");
            // 没有登录
            ObjectMapper om = new ObjectMapper();
            Map<String,Object> map = new HashMap<>();
            map.put("code",400);
            map.put("msg","用户没有登录不能访问后续接口");
            response.setContentType("application/json;charset=utf-8");
            String jsonStr = om.writeValueAsString(map);
            PrintWriter out = response.getWriter();
            out.write(jsonStr);
            out.flush();
            out.close();
            return false;
        }else{
            log.info("用户已登录");
            return true;
        }
    }
}
